package cn.ywyself.extend.directive;

import com.jfinal.template.Directive;
import com.jfinal.template.Env;
import com.jfinal.template.expr.ast.ExprList;
import com.jfinal.template.io.Writer;
import com.jfinal.template.stat.ParseException;
import com.jfinal.template.stat.Scope;

/**
 * 版本号
 * <p>
 * #ver()
 * #ver('m')
 * '0'：不改变<br>
 * 's'：每秒改变一次(默认)<br>
 * 'm'：每分钟改变一次<br>
 * 'h'：每小时改变一次<br>
 * 'd'：每天改变一次<br>
 * 'w'：每7天改变一次<br>
 * 'M'：每30天改变一次<br>
 * 'y'：每365天改变一次<br>
 *
 * @author : ywyself
 * @created : 2018-08-02 11:38
 */
public class VersionDirective extends Directive {

    @Override
    public void setExprList(ExprList exprList) {
        if (exprList.length() > 1) {
            throw new ParseException("Wrong number parameter of # directive, one parameters allowed at most", location);
        }
        super.setExprList(exprList);
    }

    @Override
    public void exec(Env env, Scope scope, Writer writer) {
        Object type = exprList != null ? exprList.eval(scope) : null;
        if (type == null) {
            write(writer, getVersion("s"));
        } else {
            write(writer, getVersion((String) type));
        }
    }

    /**
     * '0'：不改变<br>
     * 's'：每秒改变一次<br>
     * 'm'：每分钟改变一次<br>
     * 'h'：每小时改变一次<br>
     * 'd'：每天改变一次<br>
     * 'w'：每7天改变一次<br>
     * 'M'：每30天改变一次<br>
     * 'y'：每365天改变一次<br>
     */
    private String getVersion(String type) {
        switch (type != null ? type : "s") {
            case "0":
                return "";
            case "y":
                return System.currentTimeMillis() / 1000 / 60 / 60 / 24 / 365 + "";
            case "M":
                return System.currentTimeMillis() / 1000 / 60 / 60 / 24 / 30 + "";
            case "w":
                return System.currentTimeMillis() / 1000 / 60 / 60 / 24 / 7 + "";
            case "d":
                return System.currentTimeMillis() / 1000 / 60 / 60 / 24 + "";
            case "h":
                return System.currentTimeMillis() / 1000 / 60 / 60 + "";
            case "m":
                return System.currentTimeMillis() / 1000 / 60 + "";
            default:
                return System.currentTimeMillis() / 1000 + "";
        }
    }
}
